package com.wonderGirls.swGirls2.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.wonderGirls.swGirls2.MainActivity;
import com.wonderGirls.swGirls2.R;

public class GirlItemAdapter extends BaseAdapter {

	MainActivity context;
	HashMap<Integer, View> items = new HashMap<Integer, View>();
	UnlockClickListener unlockClickListener;

	public GirlItemAdapter(MainActivity context) {
		this.context = context;
		unlockClickListener = new UnlockClickListener();
	}

	@Override
	public int getCount() {
		return ResourceManager.indexList.size();
	}

	@Override
	public Object getItem(int position) {
		if (items.containsKey(position)) {
			return items.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (items.containsKey(position)) {
			View item = items.get(position);
			Button btnUnlock = (Button) item.findViewById(R.id.btnUnlock);
			if (!(ResourceManager.indexToIsLockedMap.get(position))) {
				btnUnlock.setVisibility(View.GONE);

				// ImageView imgLock = (ImageView) item
				// .findViewById(R.id.lockImage);
				// imgLock.setVisibility(View.GONE);
			}
			return items.get(position);
		}
		View item = context.getLayoutInflater()
				.inflate(R.layout.grilitem, null);
		Button btnUnlock = (Button) item.findViewById(R.id.btnUnlock);
		btnUnlock.setTag(position);
		btnUnlock.setOnClickListener(unlockClickListener);
		btnUnlock.setText(ResourceManager.getPrice(position) + "金币");
		ImageView iv = (ImageView) item.findViewById(R.id.itemImage);
		String fileName = ResourceManager.indexToResDirMap.get(position)
				+ File.separator + "thumb.jpg";
		try {
			iv.setImageBitmap(ResourceManager.getBitmapFromAsset(fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		TextView txt = (TextView) item.findViewById(R.id.txtItemName);
		txt.setText(ResourceManager.indexToGirlNameMap.get(position));
		if (!(ResourceManager.indexToIsLockedMap.get(position))) {
			// ImageView imgLock = (ImageView)
			// item.findViewById(R.id.lockImage);
			// imgLock.setVisibility(View.GONE);
			btnUnlock.setVisibility(View.GONE);
		}
		items.put(position, item);
		return item;
	}

	class UnlockClickListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			if (v instanceof Button) {
				Button btn = (Button) v;
				ResourceManager.unlockGallery((Integer) btn.getTag());
				MainActivity.instance.itemAdapter.notifyDataSetChanged();
			}
		}
	}
}
